package com.zhangmeng.online.exam.ui.api.model;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.zhangmeng.online.exam.ui.components.SendPaperComponent;
import com.zhangmeng.online.exam.ui.components.callBack.SendPaperComponentCallBackImpl;
import com.zhangmeng.online.exam.ui.utils.ApiUtils;
import com.zhangmeng.online.exam.ui.api.DataLoad;
import com.zhangmeng.online.exam.ui.components.PaperViewComponent;
import com.zhangmeng.online.exam.ui.components.callBack.PaperViewComponentCallBackImpl;
import com.zhangmeng.online.exam.ui.utils.AlertUtils;
import com.zhangmeng.online.exam.ui.utils.HttpUtils;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.Parent;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

import java.util.*;

/**
 * @author zm
 * @date 2025/3/18 17:04
 * @version: 1.0
 */
public class PaperDataLoad implements DataLoad {

    private Parent form;

    @Override
    public ApiUtils.DataView loadData(Integer pageNum, Integer pageSize) {
        Map<String, Object> params = new HashMap<>();
        params.put("pageNum", pageNum.toString());
        params.put("pageSize", pageSize.toString());
        String userListData = HttpUtils.GET(ApiUtils.API_URL + "/paper/list", params);
        JSONObject jsonObject = JSON.parseObject(userListData);
        JSONArray data = jsonObject.getJSONArray("data");
        int total = jsonObject.getIntValue("total");
        List<Map<String, SimpleStringProperty>> userMapList = new ArrayList<>();
        for (Object datum : data) {
            JSONObject paper = (JSONObject) datum;
            Map<String, SimpleStringProperty> userMap = new HashMap<>();
            userMap.put("序号", new SimpleStringProperty(paper.getString("id")));
            userMap.put("试卷名称", new SimpleStringProperty(paper.getString("name")));
            userMap.put("创建人", new SimpleStringProperty(paper.getString("creator_username")));
            userMap.put("学科名称", new SimpleStringProperty(paper.getString("subject_name")));
            userMap.put("总分", new SimpleStringProperty(paper.getString("totalScore")));
            userMap.put("考试时间", new SimpleStringProperty(paper.getString("examTime")));
            userMap.put("id", new SimpleStringProperty(paper.getString("id")));
            userMapList.add(userMap);
        }

        ApiUtils.DataView dataView = new ApiUtils.DataView(Arrays.asList("序号", "试卷名称", "创建人", "学科名称", "总分", "考试时间"), userMapList).setDataLoad(this).setPageNum(pageNum).setPageSize(pageSize).setTotal(total);
        dataView.setDataLoad(this);

        return dataView;
    }

    @Override
    public void setForm(Parent view) {
        this.form = view;
    }

    @Override
    public Parent getForm() {
        return this.form;
    }

    @Override
    public Map<String, Object> saveForm(Map<String, Object> map) {
        String result = HttpUtils.POST(ApiUtils.API_URL + "/user/save", map);
        JSONObject jsonObject = JSON.parseObject(result);
        if (jsonObject.getIntValue("code") == 200) {
            AlertUtils.alert_msg("保存成功！");
        } else {
            AlertUtils.alert_warning("保存失败！");
        }
        return null;
    }

    @Override
    public void deleteData(String id) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        String result = HttpUtils.POST(ApiUtils.API_URL + "/user/delete", map);
        JSONObject jsonObject = JSON.parseObject(result);
        if (jsonObject.getIntValue("code") == 200) {
            AlertUtils.alert_msg("删除成功！");
        } else {
            AlertUtils.alert_warning("删除失败！");
        }
    }

    @Override
    public void editData(String id, Stage stage) {


    }

    @Override
    public void updateData(String id, String name, String oldValue, String newValue) {
//        System.out.println("修改前：" + oldValue + "，修改后：" + newValue);

        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("fieldName", name);
        map.put("oldValue", oldValue);
        map.put("newValue", newValue);
        String result = HttpUtils.POST(ApiUtils.API_URL + "/user/update", map);
        JSONObject jsonObject = JSON.parseObject(result);
        if (jsonObject.getIntValue("code") == 200) {
            AlertUtils.alert_msg("更新成功！");
        } else {
            AlertUtils.alert_warning("更新失败！");
        }

    }

    @Override
    public List<MenuItem> getContextMenu() {
        //组卷
        MenuItem  group_volumes = group_volumes();

        //发卷
        MenuItem  send_paper = send_paper();

        return Arrays.asList(group_volumes,send_paper);
    }

    //发卷
    private MenuItem send_paper(){
        MenuItem group_volumes = new MenuItem("发卷");
        group_volumes.setOnAction(event -> {
            Map<String, SimpleStringProperty> map = ApiUtils.selectedItem(group_volumes);
            String id = map.get("id").getValue();
            ContextMenu parentPopup = group_volumes.getParentPopup();
            BorderPane indexPage = (BorderPane) parentPopup.getStyleableParent();
            Stage stage = (Stage) indexPage.getScene().getWindow();

            Map<String, Object> context = new HashMap<>();
            context.put("id", id);

            SendPaperComponent paperViewComponent = new SendPaperComponent(new SendPaperComponentCallBackImpl(),context);
            paperViewComponent.setPrefWidth(1200);
            paperViewComponent.setPrefHeight(649);

            AlertUtils.alert("发卷", paperViewComponent, 1200, 649, stage, true);

        });
        return group_volumes;
    }

    private MenuItem group_volumes(){
        MenuItem group_volumes = new MenuItem("组卷");
        group_volumes.setOnAction(event -> {
            Map<String, SimpleStringProperty> map = ApiUtils.selectedItem(group_volumes);
            String id = map.get("id").getValue();
//            AlertUtils.alert_msg("组卷正在开发中..." + id);
            ContextMenu parentPopup = group_volumes.getParentPopup();
            BorderPane indexPage = (BorderPane) parentPopup.getStyleableParent();
            Stage stage = (Stage) indexPage.getScene().getWindow();

            Map<String, Object> context = new HashMap<>();
            context.put("id", id);

            PaperViewComponent paperViewComponent = new PaperViewComponent(new PaperViewComponentCallBackImpl(),context);
            paperViewComponent.setPrefWidth(1200);
            paperViewComponent.setPrefHeight(649);

            AlertUtils.alert("组卷", paperViewComponent, 1200, 649, stage, true);

        });
        return group_volumes;
    }


    @Override
    public ApiUtils.DataView searchData(Map<String, Object> searchText, int pageNum, int pageSize) {
        AlertUtils.alert_msg("搜索功能正在开发中..." + JSON.toJSONString(searchText));
        return null;
    }

    public ApiUtils.DataView loadChooseQuestionData(Map<String, Object> context,Integer pageNum, Integer pageSize) {
        Map<String, Object> params = new HashMap<>();
        params.put("pageNum", pageNum.toString());
        params.put("pageSize", pageSize.toString());
        params.put("id", context.get("id"));
        String userListData = HttpUtils.GET(ApiUtils.API_URL + "/paper/chooseQuestion/list", params);
        JSONObject jsonObject = JSON.parseObject(userListData);
        JSONArray data = jsonObject.getJSONArray("data");
        int total = jsonObject.getIntValue("total");
        List<Map<String, SimpleStringProperty>> userMapList = new ArrayList<>();
        for (Object datum : data) {
            JSONObject question = (JSONObject) datum;
            Map<String, SimpleStringProperty> userMap = new HashMap<>();
            userMap.put("序号", new SimpleStringProperty(question.getString("id")));
            userMap.put("题目", new SimpleStringProperty(question.getString("name")));
            userMap.put("题目类型", new SimpleStringProperty(question.getString("type")));
            userMap.put("所属学科", new SimpleStringProperty(question.getString("subject")));
            userMap.put("分值", new SimpleStringProperty(question.getString("score")));
            userMap.put("id", new SimpleStringProperty(question.getString("id")));
            userMap.put("score", new SimpleStringProperty(question.getString("score")));
            userMap.put("type", new SimpleStringProperty(question.getString("type")));
            userMapList.add(userMap);
        }

        ApiUtils.DataView dataView = new ApiUtils.DataView(Arrays.asList("序号", "题目", "题目类型","所属学科", "分值"), userMapList).setDataLoad(this).setPageNum(pageNum).setPageSize(pageSize).setTotal(total);
        dataView.setDataLoad(this);

        return dataView;
    }
}
